package com.ruizhong.centercontroll.util;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class ArtNetUtil {

    // Art-Net协议头
    private static final byte[] ARTNET_HEADER = {
            'A', 'r', 't', '-', 'N', 'e', 't', 0,  // ID
            0x00, 0x50,                            // OpCode (ArtDmx)
            0x00, 0x0e,                            // Protocol version
            0x00,                                  // Sequence (optional)
            0x00,                                  // Physical input port
            0x00, 0x00                             // Universe (LSB first)
    };

    // DMX数据 (512个通道)
    private byte[] dmxData = new byte[512];

    // 发送Art-Net数据包
    public void sendDMX(String ipAddress, int universe) throws Exception {
        // 创建UDP Socket
        DatagramSocket socket = new DatagramSocket();

        // 准备数据包
        byte[] packetData = new byte[ARTNET_HEADER.length + dmxData.length + 2];

        // 复制协议头
        System.arraycopy(ARTNET_HEADER, 0, packetData, 0, ARTNET_HEADER.length);

        // 设置Universe (小端序)
        packetData[14] = (byte)(universe & 0xFF);
        packetData[13] = (byte)((universe >> 8) & 0xFF);

        // 设置DMX数据长度 (大端序)
        int length = dmxData.length;
        packetData[16] = (byte)((length >> 8) & 0xFF);
        packetData[17] = (byte)(length & 0xFF);

        // 复制DMX数据
        System.arraycopy(dmxData, 0, packetData, 18, dmxData.length);

        // 创建并发送UDP数据包
        InetAddress address = InetAddress.getByName(ipAddress);
        DatagramPacket packet = new DatagramPacket(
                packetData, packetData.length, address, 6454);
        socket.send(packet);

        // 关闭Socket
        socket.close();
        System.out.println("send DMX");
    }

    // 设置DMX通道值
    public void setChannel(int channel, int value) {
        if (channel >= 1 && channel <= 512 && value >= 0 && value <= 255) {
            dmxData[channel - 1] = (byte)(value & 0xFF);
        }
    }

    // 示例用法
    public static void main(String[] args) {
        try {
            ArtNetUtil controller = new ArtNetUtil();

            // 设置一些通道值
            controller.setChannel(1, 255);  // 通道1全亮
            controller.setChannel(2, 0);   // 通道2半亮
            controller.setChannel(3, 0);     // 通道3关闭

            // 发送到Art-Net转换器 (替换为实际IP和Universe)
            controller.sendDMX("192.168.1.220", 0);

            System.out.println("DMX数据已发送");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}